/**
 * 用户缓存
 */
const basics_db = require('../dbhelper/basics_db');
const md5 = require('js-md5');

class UserCache{
    
    constructor()
    {   
        this.loadAllUser();
    }

    async loadAllUser(){
        console.log("UserCache.constrcor");
        this.users = await basics_db.find("users",{});
        this.userCount = this.users.length;
        this.userCountBase = 100000;
        this.userDic = {};
        this.userOpenidDic = {};

        for(let i = 0;i<this.users.length; i++){
            this.userDic[this.users[i].uid] = this.users[i];
            if(this.users[i].wxid.length != 0){
                this.userOpenidDic[this.users[i].wxid] = this.users[i].uid;
            }            
        }
        
        //console.log(await basics_db.find('activities', {}));
    }

    async addUser_wx(openid){

        if(this.userOpenidDic[openid] != null){
            console.log("same openid");
            return;
        }
        else{
            console.log("insert user openid:"+openid);
        }

        this.userCount++;
        let insertdata = {};
        insertdata["uid"] = this.userCount + this.userCountBase;          
        insertdata["phone"] = "";   
        insertdata["wxid"] = openid;   
        insertdata["username"] = "";
        insertdata["userpass"] = "";
        insertdata["userstate"] = 1;
        insertdata["token"] = this.getToken();
        insertdata["logintime"] = new Date();
        //注意这里多线程操作，需要锁定变量this.userCount,避免多线程变量重入导致uid重复

        let dbresult = await basics_db.insert('users', insertdata);
        if(dbresult.result.ok === 1) {
            this.users.push(insertdata);
            this.userDic[insertdata.uid] = insertdata;
            this.userOpenidDic[insertdata.openid] = insertdata.uid;
        } 
        else {
            this.userCount--;
        }
    }
    
    getToken(){
        var tokenstr = (new Date()).getTime().toString();
        tokenstr += (this.userCount + this.userCountBase).toString();
        return md5(tokenstr);
    }
    checkToken(){
        //判断登陆时间，检查token是否过期
        return turn;
    }
    getUserByUid(uid){
        if(!this.checkToken()){
            return null;
        }
        else{
            return this.userDic[uid];
        }
    }
    getUserByWxid(wxid){
        if(!this.checkToken()){
            return null;
        }
        else{
            return this.userDic[this.wxid[wxid]];
        }
    }
    

}

module.exports=UserCache;